package com.zjw.zy.utils.taskpool;

import android.os.Handler;
import android.os.HandlerThread;
import android.os.Looper;

import java.util.concurrent.Executor;

/**
 * @author ：zhong.jw
 * @date ：Created in 2022/6/10 9:46
 */
public class BackGroundExecutor implements Executor {

    private final Handler mBackHandler;

    private final HandlerThread mBackHandlerThread;

    private BackGroundExecutor() {
        mBackHandlerThread = new HandlerThread("BackGround-Thread");
        mBackHandlerThread.start();

        mBackHandler = new Handler(mBackHandlerThread.getLooper());
    }

    private static final class BackGroundExecutorHolder {
        public static final BackGroundExecutor INSTANCE = new BackGroundExecutor();
    }

    public static BackGroundExecutor get() {
        return BackGroundExecutorHolder.INSTANCE;
    }

    public Handler getBackHandler() {
        return mBackHandler;
    }

    @Override
    public void execute(Runnable command) {
        if (Looper.myLooper() == Looper.getMainLooper()) {
            mBackHandler.post(command);
        } else {
            command.run();
        }
    }

    public void shutDown(){
        mBackHandlerThread.quitSafely();
    }
}
